package com.fdb.efp.esb.service.impl.sed.letter;

import java.util.Optional;

import com.fdb.efp.esb.common.client.resp.EsbRespServiceBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.fdb.basic.framework.core.constant.ESBConstant;
import com.fdb.basic.framework.core.exception.ESBException;
import com.fdb.efp.esb.service.bo.req.sed.letter.ReqSedLetterBean;
import com.fdb.efp.esb.service.bo.resp.sed.letter.RespSedLetterBean;
import com.fdb.efp.esb.service.client.ESBClientFactory;
import com.fdb.efp.esb.service.facade.sed.letter.SedLetterInformService;

/**
 * 短信通知服务<br>
 * 
 * @author zhoucs1
 * @version 1.0
 * @since 2019年4月18日 下午4:12:51
 */
@Service("sedLetterInformService")
public class SedLetterInformServiceImpl implements SedLetterInformService {

	private static Logger logger = LoggerFactory.getLogger(SedLetterInformServiceImpl.class);

	/**
	 * 
	 * 发送短信通知给短信平台<br/>
	 * 
	 * @author zhoucs1
	 * @since 2019年4月18日 下午5:24:33
	 * @param reqSedLetterBean
	 * @return
	 * @throws Exception
	 */
	@Override
	public RespSedLetterBean sendLetter(ReqSedLetterBean reqSedLetterBean) throws Exception {

		logger.debug("正在调用短信通知接口，请求参数：" + JSONObject.toJSONString(reqSedLetterBean));
		RespSedLetterBean respSedLetterBean = null;
		try {
			EsbRespServiceBean esbRespServiceBean = ESBClientFactory.buildClient().withBody(reqSedLetterBean)
					.withTradeNo(ESBConstant.SYSTEM_ID_MSP).withScene(ESBConstant.SCENE_NO_01).create()
					.sendAndReceive();
			Optional.ofNullable(esbRespServiceBean.getSysHead()).orElseThrow(()->new ESBException("访问ESB发生异常，请检查请求参数是否正确或ESB是否连通"));
			
			respSedLetterBean = esbRespServiceBean.getBody(RespSedLetterBean.class);
			
			Optional.ofNullable(respSedLetterBean).orElseThrow(()->new ESBException("短信平台未返回响应信息"));
			
			logger.info("调用短信通知接口结束，响应结果为：" + JSONObject.toJSONString(respSedLetterBean));
		} catch (ESBException e) {
			e.printStackTrace();
			logger.error("調用ESB发送短信出现异常：" + e.getMessage());
			throw new ESBException("短信发送短信出现异常：" + e.getMessage());
		}
		return respSedLetterBean;
	}
}
